<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>同步分析接口 JavaScript 调用示例</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: #fafafa;
        }
        .section h3 {
            color: #2c3e50;
            margin-top: 0;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin: 5px;
        }
        button:hover {
            background-color: #2980b9;
        }
        button:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
        }
        .log {
            background-color: #2c3e50;
            color: #ecf0f1;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            max-height: 400px;
            overflow-y: auto;
            white-space: pre-wrap;
            margin-top: 15px;
        }
        .success {
            color: #27ae60;
        }
        .error {
            color: #e74c3c;
        }
        .info {
            color: #3498db;
        }
        .config {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
        }
        .config input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .config label {
            font-weight: bold;
            color: #555;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>同步分析接口 JavaScript 调用示例</h1>
        
        <div class="section">
            <h3>📋 接口说明</h3>
            <p><strong>接口地址:</strong> POST /api/tablet/brainwave/sync</p>
            <p><strong>功能:</strong> 上传脑波数据并同步返回分析结果</p>
            <p><strong>特点:</strong> 根据数据量自动选择实时分析或YASA分析，同步等待分析完成</p>
        </div>

        <div class="section">
            <h3>⚙️ 配置参数</h3>
            <div class="config">
                <div>
                    <label for="serverUrl">服务器地址:</label>
                    <input type="text" id="serverUrl" value="http://localhost:8005" />
                </div>
                <div>
                    <label for="sessionId">会话ID:</label>
                    <input type="text" id="sessionId" value="" placeholder="自动生成" />
                </div>
                <div>
                    <label for="roomId">房间ID:</label>
                    <input type="text" id="roomId" value="test_room_js" />
                </div>
                <div>
                    <label for="requestCount">批量请求次数:</label>
                    <input type="number" id="requestCount" value="3" min="1" max="10" />
                </div>
            </div>
        </div>

        <div class="section">
            <h3>🚀 测试操作</h3>
            <button onclick="singleRequest()">单次请求测试</button>
            <button onclick="batchRequest()">批量请求测试</button>
            <button onclick="clearLog()">清空日志</button>
            <button onclick="testServerConnection()">测试服务器连接</button>
        </div>

        <div class="section">
            <h3>📊 执行日志</h3>
            <div id="log" class="log">等待操作...</div>
        </div>
    </div>

    <script>
        // 日志输出函数
        function log(message, type = 'info') {
            const logElement = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'error' : type === 'success' ? 'success' : 'info';
            logElement.innerHTML += `<span class="${className}">[${timestamp}] ${message}</span>\n`;
            logElement.scrollTop = logElement.scrollHeight;
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '日志已清空\n';
        }

        // 生成模拟脑波数据
        function generateMockBrainwaveData(sessionId, roomId) {
            // 生成512个原始EEG数据点（模拟512Hz采样率）
            const rawValue = Array.from({length: 512}, () => 
                Math.floor(Math.random() * 4096) - 2048
            );

            // 生成8个频段功率数据
            const frequencyPowers = {
                delta: Math.floor(Math.random() * 250) + 50,
                theta: Math.floor(Math.random() * 320) + 80,
                low_alpha: Math.floor(Math.random() * 400) + 100,
                high_alpha: Math.floor(Math.random() * 360) + 90,
                low_beta: Math.floor(Math.random() * 290) + 60,
                high_beta: Math.floor(Math.random() * 210) + 40,
                low_gamma: Math.floor(Math.random() * 130) + 20,
                mid_gamma: Math.floor(Math.random() * 90) + 10
            };

            return {
                session_id: sessionId,
                room_id: roomId,
                timestamp: Date.now(),
                raw_value: rawValue,
                ...frequencyPowers,
                attention: Math.floor(Math.random() * 101),
                meditation: Math.floor(Math.random() * 101),
                poor_signal: Math.floor(Math.random() * 51), // 好信号质量
                blink_strength: Math.floor(Math.random() * 256)
            };
        }

        // 调用同步分析接口
        async function callSyncAnalysisAPI(data) {
            const serverUrl = document.getElementById('serverUrl').value;
            const apiUrl = `${serverUrl}/api/tablet/brainwave/sync`;

            try {
                log(`发送同步分析请求: session_id=${data.session_id}`);
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    const result = await response.json();
                    log(`✅ 同步分析成功: ${result.message || '分析完成'}`, 'success');
                    return result;
                } else {
                    const errorText = await response.text();
                    log(`❌ 请求失败: ${response.status} - ${errorText}`, 'error');
                    return { success: false, error: `HTTP ${response.status}` };
                }
            } catch (error) {
                log(`❌ 请求异常: ${error.message}`, 'error');
                return { success: false, error: error.message };
            }
        }

        // 解析分析结果
        function parseAnalysisResult(result) {
            if (!result.success) {
                log(`分析失败: ${result.message || result.error || '未知错误'}`, 'error');
                return;
            }

            log('=== 分析结果 ===', 'success');
            log(`会话ID: ${result.session_id}`);
            log(`数据点数: ${result.received_data_points}`);
            log(`缓冲区大小: ${result.buffer_size}`);
            log(`分析耗时: ${result.analysis_duration_ms}ms`);

            // 睡眠阶段分析
            if (result.sleep_stage) {
                const stageNames = {
                    'wake': '清醒',
                    'n1': '浅睡眠N1',
                    'n2': '浅睡眠N2',
                    'n3': '深睡眠N3',
                    'rem': 'REM睡眠'
                };
                log(`睡眠阶段: ${stageNames[result.sleep_stage] || result.sleep_stage}`);
                if (result.confidence) {
                    log(`置信度: ${(result.confidence * 100).toFixed(1)}%`);
                }
            }

            // 频域功率比例
            if (result.frequency_bands) {
                log('频域功率比例:');
                for (const [band, ratio] of Object.entries(result.frequency_bands)) {
                    log(`  ${band}: ${(ratio * 100).toFixed(1)}%`);
                }
            }
        }

        // 单次请求测试
        async function singleRequest() {
            const sessionId = document.getElementById('sessionId').value || 
                             `js_test_${Date.now()}`;
            const roomId = document.getElementById('roomId').value;

            log(`开始单次请求测试: session_id=${sessionId}`, 'info');

            // 生成模拟数据
            const data = generateMockBrainwaveData(sessionId, roomId);

            // 调用接口
            const result = await callSyncAnalysisAPI(data);

            // 解析结果
            parseAnalysisResult(result);
        }

        // 批量请求测试
        async function batchRequest() {
            const sessionId = document.getElementById('sessionId').value || 
                             `js_batch_${Date.now()}`;
            const roomId = document.getElementById('roomId').value;
            const requestCount = parseInt(document.getElementById('requestCount').value);

            log(`开始批量请求测试: session_id=${sessionId}, 请求次数=${requestCount}`, 'info');

            for (let i = 0; i < requestCount; i++) {
                log(`--- 第 ${i + 1} 次请求 ---`);

                // 生成模拟数据
                const data = generateMockBrainwaveData(sessionId, roomId);

                // 调用接口
                const result = await callSyncAnalysisAPI(data);

                // 解析结果
                parseAnalysisResult(result);

                // 间隔1秒（模拟每秒一次的数据发送）
                if (i < requestCount - 1) {
                    log('等待1秒...');
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
            }

            log('批量请求测试完成', 'success');
        }

        // 测试服务器连接
        async function testServerConnection() {
            const serverUrl = document.getElementById('serverUrl').value;
            
            try {
                log('测试服务器连接...');
                const response = await fetch(`${serverUrl}/`);
                
                if (response.ok) {
                    const result = await response.json();
                    log(`✅ 服务器连接成功: ${result.message || '服务器正常'}`, 'success');
                    log(`服务器版本: ${result.version || '未知'}`);
                } else {
                    log(`❌ 服务器响应异常: ${response.status}`, 'error');
                }
            } catch (error) {
                log(`❌ 服务器连接失败: ${error.message}`, 'error');
            }
        }

        // 页面加载时初始化
        window.onload = function() {
            log('页面加载完成，准备就绪');
            log('请配置服务器地址后开始测试');
        };
    </script>
</body>
</html>